#####################################################################
# File:         ModifyModelAssessmentAccess.py
# Product:      KnowledgeEngine
#
# Copyright:    Copyright (c) 2003, Faulkner Ltd.
# Author:       Brian Oliver
#
# Description:  This file defines the ModifyModelAssessmentAccess class, 
#               an action to change the assessment access for the current user
#
# See Also:     Action, Event
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.KnowledgeEngineCore import *
from Products.KnowledgeEngine.Action import Action, ActionInfo
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## Constants
# (none)

#model assessment access modes
maam_SET = 0                            # Set the specified number of assessments for the model
maam_ADD = 1                            # Add the specified number of assessments to the model
maam_SUBTRACT = 2                       # Subtract the specified number of assessments from the model

#the display enumeration values for the model assessment access modes property
maam_DISPLAYVALUES = [("Setting Assessments To",maam_SET), ("Adding",maam_ADD), ("Subtracting",maam_SUBTRACT)]

#####################################################################
## ModifyModelAssessmentAccessInfo Class Definition
class ModifyModelAssessmentAccessInfo(ActionInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "ModifyModelAssessmentAccess"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Modify Model Assessment Access"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "mmaa"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('icon.gif', globals())
   
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ActionInfo.onConfigureProperties(self)

        #add the 'model' property        
        self.addPropertyDefinition(PropertyDefinition(identity="modelIdentity", displayName="Model", description="The model for which to modify user assessment access", propertyType=pt_STRING, propertyFormat=pf_NATIVE, hasEnumeratedValues=true, enumeratedValuesFunction=(lambda context:[('(All Models)', 'ALL')] + [(model.getTitleOrId(), model.getIdentity()) for model in context.getEnvironment().getModels()])))        
        
        #add the 'accessDelta' property        
        self.addPropertyDefinition(PropertyDefinition(identity="accessDelta", displayName="Change Access By", description="How to modify the assessment access for the user", defaultValue=maam_SET, propertyType=pt_INTEGER, propertyFormat=pf_NATIVE, propertyStructure=ps_ATOMIC, hasEnumeratedValues=true, enumeratedValuesMapping=maam_DISPLAYVALUES))        
        
        #add the 'nrAssessments' property        
        self.addPropertyDefinition(PropertyDefinition(identity="nrAssessments", displayName="# Assessments", description="The required number of assessments", defaultValue=0, propertyType=pt_INTEGER, propertyFormat=pf_NATIVE, propertyStructure=ps_ATOMIC))        

    #---------------------------------------------------------------#

#####################################################################
## ModifyModelAssessmentAccess Action Class Definition
class ModifyModelAssessmentAccess(Action):
    """
        A class to represent a simple folder that may contain Elements
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = ModifyModelAssessmentAccessInfo()
    
    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the Folder"        

        Action.__init__(self, id, identity)
                
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing
        Action.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#
    
    def execute(self, assessmentCache, previousActionSuccess=true):
        """
           Sends the message for this log action to the stdout
        """            
        
        #attempt to get the UserAccessManager for the current environment
        lUserAccessManager = self.getEnvironment().getUserAccessManager()

        #get the user (that owns the assessment)
        lUser = assessmentCache.getUser()        
        
        #do we have a user access manager AND a user
        if lUserAccessManager != None and lUser != None:

            #get the username
            lUserName = lUser.getUserName()

            #get the user access rules 
            lUserAccessRules = lUserAccessManager.getUserAccessRules(lUserName)
            
            #do we have any user access rules for the user?
            if lUserAccessRules != None:

                #determine the kind of operation
                if self.accessDelta == maam_SET:
                    lUserAccessRules.setMaxModelAssessments(self.modelIdentity, self.nrAssessments)

                elif self.accessDelta == maam_ADD:
                    lUserAccessRules.addMaxModelAssessments(self.modelIdentity, self.nrAssessments)
                
                elif self.accessDelta == maam_SUBTRACT:
                    lUserAccessRules.addMaxModelAssessments(self.modelIdentity, -self.nrAssessments)                

        else:
            #we failed to get the user access manage... so this action fails!
            return false
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(ModifyModelAssessmentAccess)

#####################################################################